package com.withyou.design_pattern.proxyPatteren;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.withyou.design_pattern.proxyPatteren.StaticProxyPatteren.Target;
import com.withyou.design_pattern.proxyPatteren.StaticProxyPatteren.TargetInterface;

/**
 * JDK 动态代理
 * 动态代理不需要实现接口,但是需要指定接口类型
 * 通过Proxy.newProxyInstance() 构造代理对象
 * @author guicheng.huang
 *
 */
public class DynamicProxyPatteren {

	static class ProxyFactory{

	    private Object target;
	    
	    public ProxyFactory(Object target){
	        this.target=target;
	    }

	    public Object getProxyInstance(){
	        return Proxy.newProxyInstance(
	                target.getClass().getClassLoader(),
	                target.getClass().getInterfaces(),
	                new InvocationHandler() {
	                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	                        System.out.println("开始老师先说开场白");
	                        //执行目标对象方法
	                        Object returnValue = method.invoke(target, args);
	            			System.out.println("结束老师总结");
	                        return returnValue;
	                    }
	                }
	        );
	    }
	}
	
	public static void main(String[] args) {
		Target ta = new Target("test", 21);
		ProxyFactory fa = new ProxyFactory(ta);
		TargetInterface tf = (TargetInterface) fa.getProxyInstance();
		tf.say();
	}
}
